﻿using System;
using System.Linq;
using PmSadis.WebFormsUi.ExpandedControls;
using DevExpress.Web.ASPxGridView;
using PmSadis.Repositories.Abstract;
using DevExpress.Web.ASPxGridLookup;
using DevExpress.Web.ASPxTabControl;
using DevExpress.Web.Data;
using System.Web.UI.WebControls;

namespace PmSadis.WebFormsUi.Operator
{
    public partial class Works : System.Web.UI.Page
    {
        private const string __operEditWorkId = "oper-edit-work-id";
        private IListRepository<Models.Work> _repo = new Repositories.WorkRepository();
        private IListRepository<Models.Unit> _repoUnits = new Repositories.UnitRepository();
        private IListRepository<Models.Material> _repoMaterials = new Repositories.MaterialRepository();
        private IListRepository<Models.WorkMaterial> _repoWorkMaterials = new Repositories.WorkMaterialRepository();
        private IListRepository<Models.Mechanism> _repoMechanisms = new Repositories.MechanismRepository();
        private IListRepository<Models.WorkMechanism> _repoWorkMechanisms = new Repositories.WorkMechanismRepository();
        private IListRepository<Models.Driver> _repoDrivers = new Repositories.DriverRepository();
        private IListRepository<Models.WorkDriver> _repoWorkDrivers = new Repositories.WorkDriverRepository();
        private IListRepository<Models.Worker> _repoWorkers = new Repositories.WorkerRepository();
        private IListRepository<Models.WorkWorker> _repoWorkWorkers = new Repositories.WorkWorkerRepository();
        
        public IQueryable<Models.Work> AllWorks()
        {
            return _repo.All.OrderBy(x => x.Name);
        }
        public int InsertWork(string name, string code, int unitId, bool useDetail)
        {
            var work = new Models.Work {
                WorkId=0,
                Name=name,
                Code=code,
                UnitId = unitId,
                WorkKind=Models.Enums.WorkKind.Simple,
                UseDetail=useDetail
            };
            return (int)_repo.Edit(work);
        }
        public void UpdateWork(int workId, DateTime dateCreate, string name, string code, int unitId, bool useDetail)
        {
            var work = new Models.Work
            {
                WorkId = workId,
                DateCreate=dateCreate,
                Name = name,
                Code = code,
                UnitId = unitId,
                WorkKind = Models.Enums.WorkKind.Simple,
                UseDetail = useDetail
            };
            _repo.Edit(work);
        }
        public void DeleteWork(int workId)
        {
            _repo.Delete(workId);
        }

        protected void gvWorks_Init(object sender, EventArgs e)
        {
            var grid = sender as ASPxGridView;
            grid.ForceDataRowType(typeof(Models.Work));
            grid.SetDefaultSettings();
        }
        protected void gvWorks_StartRowEditing(object sender, ASPxStartRowEditingEventArgs e)
        {
            Session[__operEditWorkId] = e.EditingKeyValue;
        }
        protected void gvWorks_RowInserting(object sender, ASPxDataInsertingEventArgs e)
        {
            var grid = sender as ASPxGridView;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["UnitId"] as GridViewDataColumn, "lucUnits") as ASPxGridLookup;
            var unitId = lookup.Value;
            e.NewValues["UnitId"] = Convert.ToInt32(unitId);
        }
        int _newWorkId;
        protected void dsWorks_Inserted(object sender, ObjectDataSourceStatusEventArgs e)
        {
            _newWorkId = (int)e.ReturnValue;
        }
        protected void gvWorks_RowInserted(object sender, ASPxDataInsertedEventArgs e)
        {
            var grid = sender as ASPxGridView;
            var visibleIndex=grid.FindVisibleIndexByKeyValue(_newWorkId);
            grid.StartEdit(visibleIndex);
        }
        protected void gvWorks_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
        {
            var grid = sender as ASPxGridView;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["UnitId"] as GridViewDataColumn, "lucUnits") as ASPxGridLookup;
            var unitId = lookup.Value;
            e.NewValues["UnitId"] = Convert.ToInt32(unitId);

            var dateCreate = grid.GetRowValues(index, "DateCreate");

            e.NewValues["DateCreate"] = dateCreate;
        }

        protected void editor_Init(object sender, EventArgs e)
        {
            var pageControl = sender as ASPxPageControl;
            if (gvWorks.IsNewRowEditing)
            {
                var tabNames = new string[] { "tpMaterials", "tpMechanisms", "tpDrivers", "tpWorkers" };
                tabNames.ToList().ForEach(x => {
                    pageControl.TabPages.FindByName(x).Visible = false;
                });
            }
        }

        protected void lucUnits_Init(object sender, EventArgs e)
        {
            var lookup = sender as ASPxGridLookup;
            var container = lookup.NamingContainer as GridViewDataItemTemplateContainer;
            if (!container.Grid.IsNewRowEditing)
            {
                var workId = (int)container.Grid.GetRowValues(container.VisibleIndex, container.Column.FieldName);
                lookup.GridView.Selection.SelectRowByKey(workId);
            }
        }

        public IQueryable<Models.Unit> Units()
        {
            return _repoUnits.All.OrderBy(x => x.Name);
        }

        /*Материалы*/
        public IQueryable<Models.Material> Materials()
        {
            var result=_repoMaterials.All.OrderBy(x => x.Name);
            return result;
        }

        public IQueryable<Models.WorkMaterial> WorkMaterials(int workId)
        {
            var result=_repo.All.FirstOrDefault(x => x.WorkId == workId).WorkMaterials
                .OrderBy(x=>x.Material.Name)
                .AsQueryable();
            return result;
        }
        public void InsertWorkMaterial(int materialId, int workId, double value)
        {
            var workMaterial = new Models.WorkMaterial {
                WorkMaterialId=0,
                WorkId=workId,
                MaterialId=materialId,
                Value=value
            };
            _repoWorkMaterials.Edit(workMaterial);
        }
        public void UpdateWorkMaterial(int workMaterialId, DateTime dateCreate, int materialId, int workId, double value)
        {
            var workMaterial = new Models.WorkMaterial
            {
                WorkMaterialId = workMaterialId,
                DateCreate=dateCreate,
                WorkId = workId,
                MaterialId = materialId,
                Value = value
            };
            _repoWorkMaterials.Edit(workMaterial);
        }
        public void DeleteWorkMaterial(int workMaterialId)
        {
            _repoWorkMaterials.Delete(workMaterialId);
        }

        protected void gvWorkMaterials_Init(object sender, EventArgs e)
        {
            var grid = sender as ASPxGridView;
            grid.ForceDataRowType(typeof(Models.WorkMaterial));
            grid.SetDefaultSettings();
        }
        protected void lucMaterials_Init(object sender, EventArgs e)
        {
            var lookup = sender as ASPxGridLookup;
            var container = lookup.NamingContainer as GridViewDataItemTemplateContainer;
            if (!container.Grid.IsNewRowEditing)
            {
                var materialId = (int)container.Grid.GetRowValues(container.VisibleIndex, container.Column.FieldName);
                lookup.GridView.Selection.SelectRowByKey(materialId);
            }
        }
        protected void gvWorkMaterials_RowInserting(object sender, ASPxDataInsertingEventArgs e)
        {
            var grid = sender as ASPxGridView;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["MaterialId"] as GridViewDataColumn, "lucMaterials") as ASPxGridLookup;
            var materialId = lookup.Value;
            e.NewValues["MaterialId"] = Convert.ToInt32(materialId);

            var workId = Session[__operEditWorkId];
            e.NewValues["WorkId"] = Convert.ToInt32(workId);
        }
        protected void gvWorkMaterials_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
        {
            var grid = sender as ASPxGridView;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["MaterialId"] as GridViewDataColumn, "lucMaterials") as ASPxGridLookup;
            var materialId = lookup.Value;
            e.NewValues["MaterialId"] = Convert.ToInt32(materialId);

            var workId = Session[__operEditWorkId];
            e.NewValues["WorkId"] = Convert.ToInt32(workId);

            var dateCreate = grid.GetRowValues(index, "DateCreate");
            e.NewValues["DateCreate"] = dateCreate;
        }

        /*Механизмы*/
        public IQueryable<Models.Mechanism> Mechanisms()
        {
            var result = _repoMechanisms.All.OrderBy(x => x.Name);
            return result;
        }

        public IQueryable<Models.WorkMechanism> WorkMechanisms(int workId)
        {
            var result = _repo.All.FirstOrDefault(x => x.WorkId == workId).WorkMechanisms
                .OrderBy(x => x.Mechanism.Name)
                .AsQueryable();
            return result;
        }
        public void InsertWorkMechanism(int mechanismId, int workId, double value)
        {
            var workMechanism = new Models.WorkMechanism
            {
                WorkMechanismId = 0,
                WorkId = workId,
                MechanismId = mechanismId,
                Value = value
            };
            _repoWorkMechanisms.Edit(workMechanism);
        }
        public void UpdateWorkMechanism(int workMechanismId, DateTime dateCreate, int mechanismId, int workId, double value)
        {
            var workMechanism = new Models.WorkMechanism
            {
                WorkMechanismId = workMechanismId,
                DateCreate = dateCreate,
                WorkId = workId,
                MechanismId = mechanismId,
                Value = value
            };
            _repoWorkMechanisms.Edit(workMechanism);
        }
        public void DeleteWorkMechanism(int workMechanismId)
        {
            _repoWorkMechanisms.Delete(workMechanismId);
        }

        protected void gvWorkMechanisms_Init(object sender, EventArgs e)
        {
            var grid = sender as ASPxGridView;
            grid.ForceDataRowType(typeof(Models.WorkMechanism));
            grid.SetDefaultSettings();
        }
        protected void lucMechanisms_Init(object sender, EventArgs e)
        {
            var lookup = sender as ASPxGridLookup;
            var container = lookup.NamingContainer as GridViewDataItemTemplateContainer;
            if (!container.Grid.IsNewRowEditing)
            {
                var mechanismslId = (int)container.Grid.GetRowValues(container.VisibleIndex, container.Column.FieldName);
                lookup.GridView.Selection.SelectRowByKey(mechanismslId);
            }
        }
        protected void gvWorkMechanisms_RowInserting(object sender, ASPxDataInsertingEventArgs e)
        {
            var grid = sender as ASPxGridView;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["MechanismId"] as GridViewDataColumn, "lucMechanisms") as ASPxGridLookup;
            var mechanismId = lookup.Value;
            e.NewValues["MechanismId"] = Convert.ToInt32(mechanismId);

            var workId = Session[__operEditWorkId];
            e.NewValues["WorkId"] = Convert.ToInt32(workId);
        }
        protected void gvWorkMechanisms_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
        {
            var grid = sender as ASPxGridView;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["MechanismId"] as GridViewDataColumn, "lucMechanisms") as ASPxGridLookup;
            var mechanismId = lookup.Value;
            e.NewValues["MechanismId"] = Convert.ToInt32(mechanismId);

            var workId = Session[__operEditWorkId];
            e.NewValues["WorkId"] = Convert.ToInt32(workId);

            var dateCreate = grid.GetRowValues(index, "DateCreate");
            e.NewValues["DateCreate"] = dateCreate;
        }

        /*Машинисты*/
        public IQueryable<Models.Driver> Drivers()
        {
            var result = _repoDrivers.All.OrderBy(x => x.Name);
            return result;
        }

        public IQueryable<Models.WorkDriver> WorkDrivers(int workId)
        {
            var result = _repo.All.FirstOrDefault(x => x.WorkId == workId).WorkDrivers
                .OrderBy(x => x.Driver.Name)
                .AsQueryable();
            return result;
        }
        public void InsertWorkDriver(int driverId, int workId, double value)
        {
            var workDriver = new Models.WorkDriver
            {
                WorkDriverId = 0,
                WorkId = workId,
                DriverId = driverId,
                Value = value
            };
            _repoWorkDrivers.Edit(workDriver);
        }
        public void UpdateWorkDriver(int workDriverId, DateTime dateCreate, int driverId, int workId, double value)
        {
            var workDriver = new Models.WorkDriver
            {
                WorkDriverId = workDriverId,
                DateCreate = dateCreate,
                WorkId = workId,
                DriverId = driverId,
                Value = value
            };
            _repoWorkDrivers.Edit(workDriver);
        }
        public void DeleteWorkDriver(int workDriverId)
        {
            _repoWorkDrivers.Delete(workDriverId);
        }

        protected void gvWorkDrivers_Init(object sender, EventArgs e)
        {
            var grid = sender as ASPxGridView;
            grid.ForceDataRowType(typeof(Models.WorkDriver));
            grid.SetDefaultSettings();
        }
        protected void lucDrivers_Init(object sender, EventArgs e)
        {
            var lookup = sender as ASPxGridLookup;
            var container = lookup.NamingContainer as GridViewDataItemTemplateContainer;
            if (!container.Grid.IsNewRowEditing)
            {
                var driverId = (int)container.Grid.GetRowValues(container.VisibleIndex, container.Column.FieldName);
                lookup.GridView.Selection.SelectRowByKey(driverId);
            }
        }
        protected void gvWorkDrivers_RowInserting(object sender, ASPxDataInsertingEventArgs e)
        {
            var grid = sender as ASPxGridView;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["DriverId"] as GridViewDataColumn, "lucDrivers") as ASPxGridLookup;
            var driverId = lookup.Value;
            e.NewValues["DriverId"] = Convert.ToInt32(driverId);

            var workId = Session[__operEditWorkId];
            e.NewValues["WorkId"] = Convert.ToInt32(workId);
        }
        protected void gvWorkDrivers_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
        {
            var grid = sender as ASPxGridView;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["DriverId"] as GridViewDataColumn, "lucDrivers") as ASPxGridLookup;
            var driverId = lookup.Value;
            e.NewValues["DriverId"] = Convert.ToInt32(driverId);

            var workId = Session[__operEditWorkId];
            e.NewValues["WorkId"] = Convert.ToInt32(workId);

            var dateCreate = grid.GetRowValues(index, "DateCreate");
            e.NewValues["DateCreate"] = dateCreate;
        }

        /*Рабочие*/
        public IQueryable<Models.Worker> Workers()
        {
            var result = _repoWorkers.All.OrderBy(x => x.Name);
            return result;
        }

        public IQueryable<Models.WorkWorker> WorkWorkers(int workId)
        {
            var result = _repo.All.FirstOrDefault(x => x.WorkId == workId).WorkWorkers
                .OrderBy(x => x.Worker.Name)
                .AsQueryable();
            return result;
        }
        public void InsertWorkWorker(int workerId, int workId, double value)
        {
            var workWoker = new Models.WorkWorker
            {
                WorkWorkerId = 0,
                WorkId = workId,
                WorkerId = workerId,
                Value = value
            };
            _repoWorkWorkers.Edit(workWoker);
        }
        public void UpdateWorkWorker(int workWorkerId, DateTime dateCreate, int workerId, int workId, double value)
        {
            var workWoker = new Models.WorkWorker
            {
                WorkWorkerId = workWorkerId,
                DateCreate = dateCreate,
                WorkId = workId,
                WorkerId = workerId,
                Value = value
            };
            _repoWorkWorkers.Edit(workWoker);
        }
        public void DeleteWorkWorker(int workWorkerId)
        {
            _repoWorkWorkers.Delete(workWorkerId);
        }

        protected void gvWorkWorkers_Init(object sender, EventArgs e)
        {
            var grid = sender as ASPxGridView;
            grid.ForceDataRowType(typeof(Models.WorkWorker));
            grid.SetDefaultSettings();
        }
        protected void lucWorkers_Init(object sender, EventArgs e)
        {
            var lookup = sender as ASPxGridLookup;
            var container = lookup.NamingContainer as GridViewDataItemTemplateContainer;
            if (!container.Grid.IsNewRowEditing)
            {
                var workerId = (int)container.Grid.GetRowValues(container.VisibleIndex, container.Column.FieldName);
                lookup.GridView.Selection.SelectRowByKey(workerId);
            }
        }
        protected void gvWorkWorkers_RowInserting(object sender, ASPxDataInsertingEventArgs e)
        {
            var grid = sender as ASPxGridView;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["WorkerId"] as GridViewDataColumn, "lucWorkers") as ASPxGridLookup;
            var workerId = lookup.Value;
            e.NewValues["WorkerId"] = Convert.ToInt32(workerId);

            var workId = Session[__operEditWorkId];
            e.NewValues["WorkId"] = Convert.ToInt32(workId);
        }
        protected void gvWorkWorkers_RowUpdating(object sender, ASPxDataUpdatingEventArgs e)
        {
            var grid = sender as ASPxGridView;

            var index = grid.EditingRowVisibleIndex;
            var lookup = grid.FindEditRowCellTemplateControl(grid.Columns["WorkerId"] as GridViewDataColumn, "lucWorkers") as ASPxGridLookup;
            var workerId = lookup.Value;
            e.NewValues["WorkerId"] = Convert.ToInt32(workerId);

            var workId = Session[__operEditWorkId];
            e.NewValues["WorkId"] = Convert.ToInt32(workId);

            var dateCreate = grid.GetRowValues(index, "DateCreate");
            e.NewValues["DateCreate"] = dateCreate;
        }
    }
}